import 'dart:async';
import 'package:amap_flutter_location/amap_flutter_location.dart';
import 'package:amap_flutter_location/amap_location_option.dart';
import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:permission_handler/permission_handler.dart';
import '../../../utils/common_widget.dart';
import 'package:amap_flutter_map/amap_flutter_map.dart';
import '../../../utils/map/map_common_config.dart';
import 'package:amap_flutter_base/amap_flutter_base.dart';
import 'dart:io';
import 'address_chose_controller.dart';
import 'package:get/get.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'address_chose_search_page.dart';
import 'adress_chose_poi_model.dart';

class AddressChosePage extends StatefulWidget {
  Function? finishBlock;

  AddressChosePage({Key? key, this.finishBlock}) : super(key: key);

  @override
  State<AddressChosePage> createState() => _AddressChosePageState();
}

class _AddressChosePageState extends State<AddressChosePage> {
  late AMapController _mapController;
  LatLng? latLng;
  late CameraPosition kInitialPosition;
  late Map<String, Object> _locationResult;

  late StreamSubscription<Map<String, Object>> _locationListener;

  AMapFlutterLocation _locationPlugin = new AMapFlutterLocation();

  AddressChoseController addressController = Get.put(AddressChoseController());

  @override
  Widget build(BuildContext context) {
    return AppWidget.navTitleBar(
      bgColor: ThemeColor.grayF9F9F9Color,
      title: '选择地址',
      childWidget: Column(
        children: [
          GestureDetector(
            onTap: () {
              Get.to(AddressChoseSearchPage(finishBlock: widget.finishBlock,));
            },
            child: Container(
              margin: const EdgeInsets.symmetric(vertical: 10, horizontal: 15),
              padding: const EdgeInsets.symmetric(vertical: 10),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(4),
                color: Colors.white,
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Image.asset(
                    'images/map/search_mirror_big.png',
                    width: 15,
                  ),
                  const SizedBox(width: 5,),
                  const Text('搜索',
                      style: TextStyle(
                        fontSize: 16,
                        color: Color(0xFFB3B3B3),
                      )),
                ],
              ),
            ),
          ),
          getMapView(),
          SizedBox(
            height: 1.sh -
                238.w -
                ScreenUtil().statusBarHeight -
                ScreenUtil().bottomBarHeight -
                55 -
                70,
            child: GetBuilder(
                id: addressController.poiViewId,
                builder: (AddressChoseController controller) {
                  return ListView.builder(
                    itemBuilder: (BuildContext context, int index) {
                      AddressChosePoiDataModel dataModel =
                          controller.addressList[index];
                      return getAddressListView(dataModel);
                    },
                    itemCount: controller.addressList.length,
                  );
                }),
          ),
        ],
      ),
    );
  }

  Widget getAddressListView(AddressChosePoiDataModel model) {
    return CupertinoButton(
      padding: EdgeInsets.zero,
      onPressed: () {
        if (model.isChose) {
          return;
        }
        addressController.addressList.forEach((element) {
          if (element.address == model.address) {
            element.isChose = true;
          } else {
            element.isChose = false;
          }
        });
        addressController.update([addressController.poiViewId]);
      },
      child: Stack(
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(
                height: 18.h,
              ),
              Padding(
                padding: EdgeInsets.only(left: 16.w),
                child: Text(
                  model.name ?? '',
                  style: TextStyle(fontSize: 16.sp, color: Color(0xFF3A3A3A)),
                ),
              ),
              SizedBox(
                height: 6.h,
              ),
              Padding(
                padding: EdgeInsets.only(left: 16.w),
                child: Text(
                  model.address ?? '',
                  style: TextStyle(
                      fontSize: 12.sp, color: ThemeColor.textColorSecond),
                ),
              ),
              SizedBox(
                height: 10.h,
              ),
              Container(
                color: ThemeColor.lineColor,
                height: 0.5,
              ),
            ],
          ),
          Positioned(
            top: 0,
            bottom: 0,
            right: 16,
            child: Visibility(
              visible: model.isChose,
              child: GestureDetector(
                onTap: (){
                  AddressChosePoiDataModel choseModel = addressController
                      .addressList
                      .singleWhere((element) => element.isChose);
                  if (widget.finishBlock != null) {
                    widget.finishBlock!(choseModel);
                  }
                  Get.back();
                },
                child: Center(
                  child: Text('确定',style:TextStyle(color: ThemeColor.appColor,fontSize: 14),),
                ),
              ),


            ),
          ),
        ],
      ),
    );
  }

  Widget getMapView() {
    return SizedBox(
      width: 1.sw,
      height: 238.w,
      child: GetBuilder(
          id: addressController.mapViewId,
          builder: (AddressChoseController controller) {
            return AMapWidget(
              initialCameraPosition: kInitialPosition,
              privacyStatement: MapCommonConfig.mapPrivacyStatement,
              apiKey: MapCommonConfig.mapApiKeys,
              onMapCreated: onMapCreated,
              onLocationChanged: _onLocationChanged,
              myLocationStyleOptions: MyLocationStyleOptions(
                true,
                circleFillColor: Colors.lightBlue,
                circleStrokeColor: Colors.blue,
                circleStrokeWidth: 1,
              ),
            );
          }),
    );
  }

  void onMapCreated(AMapController controller) {
    _mapController = controller;
    _mapController.getMapContentApprovalNumber();
   // addressController.update([addressController.mapViewId]);
    getCurrentLocation();
  }

  void _onLocationChanged(AMapLocation location) {
    if (null == location) {
      return;
    }
    print('_onLocationChanged ${location.toJson()}');
    List latList = location.toJson()['latlng'];
    if (latList.first > 0 && addressController.isGetLocations == false) {
      addressController.isGetLocations = true;
      double latitude = latList.first;
      double longitude = latList.last;
      changeCenterPosition(latitude, longitude);
    }
  }

  @override
  void initState() {
    super.initState();
    // _requestLocationPermission();
    kInitialPosition =
        const CameraPosition(target: LatLng(39.909187, 116.397451), zoom: 10);
  }

  void getCurrentLocation() async {
    /// [hasShow] 隐私权政策是否弹窗展示告知用户
    AMapFlutterLocation.updatePrivacyShow(true, true);

    /// [hasAgree] 隐私权政策是否已经取得用户同意
    AMapFlutterLocation.updatePrivacyAgree(true);

    /// 动态申请定位权限
    requestPermission();
    AMapFlutterLocation.setApiKey(
        MapCommonConfig.androidKey, MapCommonConfig.iosMapKey);

    ///iOS 获取native精度类型
    if (Platform.isIOS) {
      requestAccuracyAuthorization();
    }
    _startLocation();

    ///注册定位结果监听
    _locationListener = _locationPlugin
        .onLocationChanged()
        .listen((Map<String, Object> result) {
      print('定位结果：$result');
      addressController.isGetLocations = true;
      _locationResult = result;
      double latitude = double.parse(result['latitude'].toString());
      double longitude = double.parse(result['longitude'].toString());
        changeCenterPosition(latitude, longitude);
        fetchNearbyPlaces(latitude, longitude, 10);
    });
  }

  void changeCenterPosition(double latitude, double longitude) {
    _mapController.moveCamera(
      CameraUpdate.newCameraPosition(
        CameraPosition(
            //中心点
            target: LatLng(latitude, longitude),
            //缩放级别
            zoom: 17,
            //俯仰角0°~45°（垂直与地图时为0）
            tilt: 30,
            //偏航角 0~360° (正北方为0)
            bearing: 0),
      ),
      animated: true,
    );
    addressController.update([addressController.mapViewId]);
  }

  /// 动态申请定位权限
  void requestPermission() async {
    // 申请权限
    bool hasLocationPermission = await requestLocationPermission();
    if (hasLocationPermission) {
      print("定位权限申请通过");
    } else {
      print("定位权限申请不通过");
    }
  }

  /// 申请定位权限
  /// 授予定位权限返回true， 否则返回false
  Future<bool> requestLocationPermission() async {
    //获取当前的权限
    var status = await Permission.location.status;
    if (status == PermissionStatus.granted) {
      //已经授权
      return true;
    } else {
      //未授权则发起一次申请
      status = await Permission.location.request();
      if (status == PermissionStatus.granted) {
        return true;
      } else {
        return false;
      }
    }
  }

  ///获取iOS native的accuracyAuthorization类型
  void requestAccuracyAuthorization() async {
    AMapAccuracyAuthorization currentAccuracyAuthorization =
        await _locationPlugin.getSystemAccuracyAuthorization();
    if (currentAccuracyAuthorization ==
        AMapAccuracyAuthorization.AMapAccuracyAuthorizationFullAccuracy) {
      print("精确定位类型");
    } else if (currentAccuracyAuthorization ==
        AMapAccuracyAuthorization.AMapAccuracyAuthorizationReducedAccuracy) {
      print("模糊定位类型");
    } else {
      print("未知定位类型");
    }
  }

  ///设置定位参数
  void _setLocationOption() {
    if (null != _locationPlugin) {
      AMapLocationOption locationOption = new AMapLocationOption();

      ///是否单次定位
      locationOption.onceLocation = true;

      ///是否需要返回逆地理信息
      locationOption.needAddress = true;

      ///逆地理信息的语言类型
      locationOption.geoLanguage = GeoLanguage.DEFAULT;

      locationOption.desiredLocationAccuracyAuthorizationMode =
          AMapLocationAccuracyAuthorizationMode.ReduceAccuracy;

      locationOption.fullAccuracyPurposeKey = "AMapLocationScene";

      ///设置Android端连续定位的定位间隔
      locationOption.locationInterval = 2000;

      ///设置Android端的定位模式<br>
      ///可选值：<br>
      ///<li>[AMapLocationMode.Battery_Saving]</li>
      ///<li>[AMapLocationMode.Device_Sensors]</li>
      ///<li>[AMapLocationMode.Hight_Accuracy]</li>
      locationOption.locationMode = AMapLocationMode.Hight_Accuracy;

      ///设置iOS端的定位最小更新距离<br>
      locationOption.distanceFilter = -1;

      ///设置iOS端期望的定位精度
      /// 可选值：<br>
      /// <li>[DesiredAccuracy.Best] 最高精度</li>
      /// <li>[DesiredAccuracy.BestForNavigation] 适用于导航场景的高精度 </li>
      /// <li>[DesiredAccuracy.NearestTenMeters] 10米 </li>
      /// <li>[DesiredAccuracy.Kilometer] 1000米</li>
      /// <li>[DesiredAccuracy.ThreeKilometers] 3000米</li>
      locationOption.desiredAccuracy = DesiredAccuracy.HundredMeters;

      ///设置iOS端是否允许系统暂停定位
      locationOption.pausesLocationUpdatesAutomatically = false;

      ///将定位参数设置给定位插件
      _locationPlugin.setLocationOption(locationOption);
    }
  }

  ///开始定位
  void _startLocation() {
    if (null != _locationPlugin) {
      ///开始定位之前设置定位参数
      _setLocationOption();
      _locationPlugin.startLocation();
    }
  }

  ///停止定位
  void _stopLocation() {
    if (null != _locationPlugin) {
      _locationPlugin.stopLocation();
    }
  }

  fetchNearbyPlaces(double latitude, double longitude, double radius) async {
    final apiKey = '1761005a13eece489b7a82787464fde0';
    final url =
        'https://restapi.amap.com/v3/place/around?key=$apiKey&location=$longitude,$latitude&radius=$radius&page=1&0ffset=20';
    print('请求$url');
    final response = await http.get(Uri.parse(url));
    if (response.statusCode == 200) {
      final jsonData = json.decode(response.body);
      // 在jsonData中处理周边信息
      print('拿到的数据$jsonData');
      AddressChosePoiModel chosePoiModel =
          AddressChosePoiModel.fromJson(jsonData);
      print('数据长度${chosePoiModel.poi?.length}');
      addressController.addressList.addAll(chosePoiModel.poi ?? []);
      addressController.update([addressController.poiViewId]);
    } else {
      throw Exception('Failed to load nearby places');
    }
  }
}
